#!/usr/bin/env node

import { execSync } from 'child_process'
import { existsSync, mkdirSync } from 'fs'
import { join } from 'path'

const PUBLIC_DIR = 'public'
const SOURCE_ICON = join(PUBLIC_DIR, 'icon.png')

console.log('🎨 Generating application icons...\n')

// 检查源图标是否存在
if (!existsSync(SOURCE_ICON)) {
  console.error(`❌ Source icon not found: ${SOURCE_ICON}`)
  console.log('Please ensure you have a icon.png file in the public directory')
  process.exit(1)
}

try {
  // 检查是否安装了ImageMagick (用于转换图标)
  try {
    execSync('magick -version', { stdio: 'pipe' })
    console.log('✅ ImageMagick found')
  } catch (e) {
    console.log('⚠️  ImageMagick not found. Installing via package manager...')
    
    // 尝试安装ImageMagick
    const platform = process.platform
    if (platform === 'win32') {
      console.log('Please install ImageMagick from: https://imagemagick.org/script/download.php#windows')
    } else if (platform === 'darwin') {
      console.log('Installing ImageMagick via Homebrew...')
      execSync('brew install imagemagick', { stdio: 'inherit' })
    } else {
      console.log('Installing ImageMagick via apt...')
      execSync('sudo apt-get install imagemagick', { stdio: 'inherit' })
    }
  }

  // 生成Windows ICO文件
  console.log('🖼️  Generating Windows icon (ICO)...')
  const icoSizes = [16, 24, 32, 48, 64, 128, 256]
  const icoFiles = icoSizes.map(size => {
    const tempFile = join(PUBLIC_DIR, `icon-${size}.png`)
    execSync(`magick "${SOURCE_ICON}" -resize ${size}x${size} "${tempFile}"`)
    return tempFile
  })
  
  execSync(`magick ${icoFiles.join(' ')} "${join(PUBLIC_DIR, 'icon.ico')}"`)
  
  // 清理临时文件
  icoFiles.forEach(file => {
    try {
      execSync(`rm "${file}"`)
    } catch (e) {
      // Windows
      try {
        execSync(`del "${file}"`)
      } catch (e2) {
        // 忽略清理错误
      }
    }
  })

  // 生成macOS ICNS文件
  console.log('🍎 Generating macOS icon (ICNS)...')
  const icnsDir = join(PUBLIC_DIR, 'icon.iconset')
  
  if (!existsSync(icnsDir)) {
    mkdirSync(icnsDir)
  }
  
  const icnsSizes = [
    { size: 16, name: 'icon_16x16.png' },
    { size: 32, name: 'icon_16x16@2x.png' },
    { size: 32, name: 'icon_32x32.png' },
    { size: 64, name: 'icon_32x32@2x.png' },
    { size: 128, name: 'icon_128x128.png' },
    { size: 256, name: 'icon_128x128@2x.png' },
    { size: 256, name: 'icon_256x256.png' },
    { size: 512, name: 'icon_256x256@2x.png' },
    { size: 512, name: 'icon_512x512.png' },
    { size: 1024, name: 'icon_512x512@2x.png' }
  ]
  
  icnsSizes.forEach(({ size, name }) => {
    execSync(`magick "${SOURCE_ICON}" -resize ${size}x${size} "${join(icnsDir, name)}"`)
  })
  
  // 转换为ICNS
  if (process.platform === 'darwin') {
    execSync(`iconutil -c icns "${icnsDir}" -o "${join(PUBLIC_DIR, 'icon.icns')}"`)
  } else {
    // 在非macOS平台上使用ImageMagick
    execSync(`magick "${join(icnsDir, 'icon_512x512.png')}" "${join(PUBLIC_DIR, 'icon.icns')}"`)
  }
  
  // 清理iconset目录
  execSync(`rm -rf "${icnsDir}"`)

  console.log('\n✅ Icons generated successfully!')
  console.log(`   Windows: ${join(PUBLIC_DIR, 'icon.ico')}`)
  console.log(`   macOS: ${join(PUBLIC_DIR, 'icon.icns')}`)
  console.log(`   Linux: ${SOURCE_ICON}`)

} catch (error) {
  console.error('\n❌ Icon generation failed!')
  console.error(`Error: ${error.message}`)
  
  console.log('\n💡 Manual steps:')
  console.log('1. Install ImageMagick: https://imagemagick.org/script/download.php')
  console.log('2. For Windows ICO: Use online converter or GIMP')
  console.log('3. For macOS ICNS: Use Icon Composer or online converter')
  console.log('4. Place generated files in public/ directory')
  
  process.exit(1)
}